package com.example.ai.controller;

import com.example.ai.entity.AIRequest;
import com.example.ai.service.OpenAIService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;


@RestController
@RequestMapping("/openai")
public class OpenAIController {
    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(OpenAIController.class);

    @Autowired
    private OpenAIService openAIService;

    @GetMapping("/chat")
    public Mono<String> chat(@Valid AIRequest request,
                             @RequestParam(defaultValue = "qianwen") String provider) {
        return openAIService.chat(request, provider);
    }


    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> streamChat(
            @Valid AIRequest request,
            @RequestParam(defaultValue = "qianwen") String provider,
            @RequestHeader("X-User-Id") String userId) {
        Flux<ServerSentEvent<String>> serverSentEventFlux = openAIService.streamCompletion(request, provider, userId)
                .onBackpressureBuffer(50) // 背压控制
                .timeout(Duration.ofMinutes(5)) // 超时设置
                .doOnCancel(() -> logger.info("客户端断开连接"));

        return serverSentEventFlux;
    }
}
